
新建一个CodeController.php控制器
<?php
	namespace app\controllers;
	use yii\web\Controller;

	class CodeController extends Controller {
		public function actionVerifyCode(){

		}
	}

	?>

新建Code.php模型
<?php
	namespace app\models;
	use yii\base\Model;

	class Code extends Model {
		public $code;
		public function rules() {
			return [
					[
						'code', 'captcha', 'captchaAction' => 'code/captcha',
						'message' => '验证码错误！'
					]
			];
		}
	}
	?>

新建视图@views\code\verifycode.php
<?php
	use \yii\helpers\Html;
?>
修改Code控制器actionVerifyCode操作和新增actions方法
<?php
	namespace app\controllers;
	use yii\web\Controller;

	class CodeController extends Controller {
		public function acitons() {
			return [
					'captcha'=>[
							'class'=>'yii\captcha\captchaAction',
							'maxLength'=>4,
							'minLength'=>4,
							'width'=>80,
							'height'=>40
					]
			];
		}

		public function actionVerifyCode() {
			$model = new \app\models\Code();
			if (\Yii::$app->rquest->isPost && $model->load(\Yii::$app->request->post())) {
				if ($model -> validate()) {
					echo "验证成功！";
				} else {
					var_dump($model -> getErrors());
				}
			}
			return $this->render('verifycode', ['model'=>$model]);
		}
	}
	?>


修改视图代码，加载模型数据和验证码
<?php
	use \yii\helpers\Html;
?>

<?=Html::beginForm('', 'post')?>
	<?=\yii\captcha\Captcha::widget([
					'model' => $model,
					'attribute' => 'code',							//表单字段（属性）
					'captcahAction' => 'code/captcha',	//与模型关联的验证码操作，由actions()定义
					'template' => '{input}{image}',			//模板，可以自定义
					'options' => [											//input属性数组
							'class' => 'form-control',
							'id' => 'verify'
					],
					'imageOptions' => [									//image属性数组
							'class' => 'imageCode',
							'alt' => '点击图片刷新'
					]
		]);
		?>

		<?=Html::submitButton('验证', ['class' => 'btn btn-primary'])?>
	<?=Html::endForm()?>

访问URL：http://localhost/web/index.php/r=code/verify-code

